//
//  InsuranceDetailController.m
//  iCarStyle
//
//  Created by liunian on 13-9-17.
//  Copyright (c) 2013年 liunian. All rights reserved.
//

#import "InsuranceDetailController.h"
#import "InsuranceController.h"
#import "ChexianCell.h"
#import "HttpRequest.h"

@implementation ChexianItem

@end

@interface InsuranceDetailController ()<UITableViewDataSource,UITableViewDelegate>
@property (nonatomic, retain) Insurance *insurance;
@property (nonatomic, retain) NSMutableArray *datasource;
@property (nonatomic, retain) UITableView *tableView;

@property (nonatomic, retain) UIImageView          *navImageView;
@property (nonatomic, retain) UIImageView          *bottomImageView;
@property (nonatomic, retain) UILabel       *theTitle;
@property (nonatomic, retain) UIActivityIndicatorView *indicatorView;
@end

@implementation InsuranceDetailController

- (id)initWithInsurance:(Insurance *)insurance
{
    self = [super init];
    if (self) {
        // Custom initialization
        self.insurance = insurance;
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    self.view.backgroundColor = COLOR_RGB(248, 248, 248);
    
    [self.view addSubview:self.navImageView];
    [self.view addSubview:self.bottomImageView];
    [self.theTitle setText:@"计算结果"];
    [self.indicatorView startAnimating];
    [self requestChexian];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
#define kChexianAPI  @"http://chexian.kakamobi.com/gateway"

- (NSString *)getIns{
    NSString *insStr = nil;
    
    switch (self.insurance.insuranceType) {
        case PINGAN:
            insStr = @"平安";
            break;
        case YANGGUANG:
            insStr = @"阳光";
            break;
        case RENBAO:
            insStr = @"人保";
            break;
        case TAIPINGYANG:
            insStr = @"太平洋";
            break;
        case DADI:
            insStr = @"大地";
            break;
        default:
            break;
    }
    return insStr;
}


- (void)back{
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)requestChexian{
    NSMutableDictionary *param = [NSMutableDictionary dictionaryWithCapacity:5];
    SET_PARAM(@"0", @"mobile", param);
    SET_PARAM(self.insurance.year, @"year", param);
    SET_PARAM(self.insurance.price, @"price", param);
    SET_PARAM(self.insurance.expireMonth, @"expiredMonth", param);
    SET_PARAM(@"iPhone", @"platform", param);
    SET_PARAM(@"chexiandaren", @"product", param);
    SET_PARAM(@"3.9", @"version", param);
    SET_PARAM(@"", @"imei", param);
    if (!self.insurance.isNewCar) {
        SET_PARAM(self.insurance.license, @"carno", param);//车牌号
    }else{
        SET_PARAM(@"", @"carno", param);//车牌号
    }
    
    NSString *insStr = [NSString stringWithFormat:@"%@",[self getIns]];
    SET_PARAM(insStr, @"ins", param);
    
    NSString *isNewCarStr = [NSString stringWithFormat:@"isNewCar:%d@gender:男@fullname:",self.insurance.isNewCar ? 1 : 0];
    SET_PARAM(isNewCarStr, @"extra", param);
    
    SET_PARAM(@"upload", @"action", param);
    SET_PARAM(@"", @"realCarno", param);


    [[HttpRequest sharedClient] GET:kChexianAPI parameters:param success:^(NSURLSessionDataTask *task, id responseObject) {

        NSDictionary *jsonDict = responseObject;
        BMLog(@"jsonDict:%@",jsonDict);
        if (![[jsonDict objectForKey:@"result"] boolValue]) {
            return ;
        }
        NSMutableArray *rstArray = [NSMutableArray arrayWithCapacity:0];
        NSArray *sources = [jsonDict objectForKey:@"data"];

        if (isArrayWithCountMoreThan0(sources)) {
            for (NSDictionary *dic in sources) {
                if (isDictWithCountMoreThan0(dic)) {
                    ChexianItem *item = [[ChexianItem alloc] init];
                    item.artualPrice = [[dic objectForKey:@"actualPrice"] stringValue];
                    item.marketPrice = [[dic objectForKey:@"marketPrice"] stringValue];
                    item.scope = [dic objectForKey:@"scope"];
                    item.type = [dic objectForKey:@"type"];
                    [rstArray addObject:item];
                }
            }
            [self.datasource addObjectsFromArray:rstArray];
        }

        [self.tableView reloadData];
        [self.indicatorView stopAnimating];
    } failure:^(NSURLSessionDataTask *task, NSError *error) {
        [self.indicatorView stopAnimating];
    }];
}

#pragma mark UITableViewDataSource,UITableViewDelegate
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return [self.datasource count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath;
{
    static NSString *identifier = @"detail";
    ChexianCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
    if (cell == nil) {
        cell = [[ChexianCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:identifier];
        [cell setAccessoryType:UITableViewCellAccessoryNone];
        [cell setSelectionStyle:UITableViewCellSelectionStyleGray];
    }
    ChexianItem *item = [self.datasource objectAtIndex:indexPath.row];
    [cell updateWithChexian:item];
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{

    ChexianItem *item = [self.datasource objectAtIndex:indexPath.row];
    
    CGSize size;
    size = [item.scope sizeWithFont:FONT_CONTENT(16.0f) constrainedToSize:CGSizeMake(280, 1000.0f) lineBreakMode:1];
    return 70+size.height;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
}

#pragma mark getter
- (UIImageView *)navImageView{
    if (!_navImageView) {
        _navImageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 320, 44)];
        _navImageView.userInteractionEnabled = YES;
        _navImageView.backgroundColor = [UIColor blackColor];
        [self.indicatorView setFrame:CGRectMake(CGRectGetWidth(_navImageView.frame) - 36 - 10, 5, 36, 36)];
        [_navImageView addSubview:self.indicatorView];
        
    }
    return _navImageView;
}
- (UIActivityIndicatorView *)indicatorView{
    if (!_indicatorView) {
        _indicatorView = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
        _indicatorView.hidesWhenStopped = YES;
    }
    return _indicatorView;
}
- (UILabel *)theTitle{
    if (!_theTitle) {
        _theTitle = [[UILabel alloc] initWithFrame:CGRectMake(10, 0, 260, 44)];
        _theTitle.backgroundColor = [UIColor clearColor];
        _theTitle.textAlignment = [Util getAlign:ALIGNTYPE_LEFT];
        _theTitle.font = FONT_TITLE(22.0f);
        _theTitle.textColor = [UIColor flatWhiteColor];
        [self.navImageView addSubview:_theTitle];
    }
    return _theTitle;
}
- (UIImageView *)bottomImageView{
    if (!_bottomImageView) {
        _bottomImageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, self.view.bounds.size.height - 38, 320, 38)];
        _bottomImageView.backgroundColor = [UIColor flatWhiteColor];
        _bottomImageView.userInteractionEnabled = YES;
        UIImage *imgBack = IMGNAMED(@"btn_back.png");
        UIButton *back = [UIButton buttonWithType:UIButtonTypeCustom];
        back.exclusiveTouch = YES;
        back.frame = CGRectMake(10, floorf((_bottomImageView.bounds.size.height-imgBack.size.height)/2), imgBack.size.width, imgBack.size.height);
        [back addTarget:self action:@selector(back) forControlEvents:UIControlEventTouchUpInside];
        [_bottomImageView addSubview:back];
        [back setBackgroundImage:IMGNAMED(@"btn_back.png") forState:UIControlStateNormal];
        [back setBackgroundImage:IMGNAMED(@"btn_back_light.png") forState:UIControlStateHighlighted];
    }
    return _bottomImageView;
}

- (NSMutableArray *)datasource{
    if (!_datasource) {
        _datasource = [[NSMutableArray alloc] initWithCapacity:0];
    }
    return _datasource;
}

- (UITableView *)tableView{
    if (!_tableView) {
        _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0,
                                                                   self.navImageView.frame.origin.y+self.navImageView.bounds.size.height,
                                                                   320,
                                                                   self.view.bounds.size.height - 38-self.navImageView.frame.origin.y-self.navImageView.bounds.size.height)
                                                  style:UITableViewStylePlain];
        [_tableView setBackgroundColor:[UIColor whiteColor]];
        [_tableView setBackgroundView:nil];
        [_tableView setContentInset:UIEdgeInsetsMake(0, 0, 0, 0)];
        [_tableView setSeparatorStyle:UITableViewCellSeparatorStyleSingleLine];
        [_tableView setShowsVerticalScrollIndicator:NO];
        [_tableView setDataSource:self];
        [_tableView setDelegate:self];
        [self.view addSubview:_tableView];
    }
    return _tableView;
}

@end
